import config from './config.js'
import {
	apiLogin
} from './common'
import store from '../store/index.js'
const {
	base_url
} = config;
/**
 * 封装网球请求接口
 * @param {String} url 请求地址
 * @param {Object} data 请求数据
 * @param {String} method 请求方式
 */
const request = ({
	url,
	data = null,
	headers = null,
	isToken = true,
	method = "POST",
	loading = true,
	checkToken = false,
	refreshToken = true,
	goLogin = false,
	loadMsg = ''

} = {}) => {
	if (loading) {
		uni.showLoading({
			mask: true,
			content: loadMsg
			//   delay: 1000,
		});
	}
	const _token = store.state.token
	const _url = `${base_url}${url}`;
	// GET请求方式x-www-form-urlencoded, 其他请求方式json
	let _header = headers || {
		"Content-Type": `application/${method === "GET" ? "x-www-form-urlencoded" : "json"
      }`
	};
	if (isToken) {
		_header = {
			..._header,
			'Authorization': `${_token}`
		}
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: _url,
			method: method,
			data: data,
			header: _header,
			success: res => {
				uni.hideLoading();
				console.log(`${method}接口请求成功:${_url};_____参数====>`, data, '接口相应：resoponse===>',
					res);
				if (res.statusCode === 200 && res.data.code == 200) {
					resolve(res.data);
				} else {
					if (res.data.code === 401) {
						store.commit('SET_USERINFO', {})
						store.commit('SET_TOKEN', '')
						if (refreshToken) { //刷新token
							store.dispatch('ASYNC_LOGIN', () => {
								resolve(request({
									url,
									data,
									headers,
									isToken,
									method
								}))
							})
							return false
						}
						if (goLogin) { //接口验证
							uni.showModal({
								title: '提示',
								content: '是否立即登录？',
								success: function(res) {
									if (res.confirm) {
										store.dispatch('ASYNC_LOGIN', () => {
											resolve(request({
												url,
												data,
												headers,
												isToken,
												method
											}))
										})
										return false
									}
								},
								fail: function(err) {
									console.log(err);
								}
							});
						}
					} else if (res.data.code === 600) {
						uni.showToast({
							content: res.data.msg || '网络错误'
							//   duration: 2000
						});
						reject(res.data);
					} else if (res.data.code === 700) {
						resolve(res.data);
					} else {
						uni.showToast({
							content: res.data.msg || '网络错误'
							//   duration: 2000
						});
						reject(null);
					}
				}
			},
			fail: err => {
				console.log('request:======err', err);
				if (loading) {
					uni.hideLoading();
				}
				uni.showToast({
					content: err.data.msg || '服务异常'
					//   duration: 2000
				});
				reject(err.data);
			},
			complete: res => {
				// 加载完成
			}
		});
	});
};
export default {
	base_url,
	request
};